from typing import Awaitable, Callable

from fastapi import Request, Response
from jose.exceptions import ExpiredSignatureError

from src.api.providers.auth import AuthProvider
from src.config import load_config


async def refresh_token_middleware(
    request: Request,
    call_next: Callable[[Request], Awaitable[Response]],
):
    """Обновляем jwt токен и записываем в response headers"""

    token = request.headers.get("Authorization", "").replace("Bearer ", "")
    response: Response = await call_next(request)

    if token:
        config = load_config()
        auth_provider = AuthProvider(config.auth)
        try:
            phone = auth_provider.decode_token(token)
            token = auth_provider.create_user_token(phone)
            response.headers.update({"Authorization": f"Bearer {token.access_token}"})
        except ExpiredSignatureError:
            pass

    return response
